'''
python模拟JavaScript
'''
# 验证库有没有安装成功
# import execjs
# print(execjs.get().name)

# 模拟代码
# import execjs
# import json
#
# item = {
#     'name': '凯文-杜兰特',
#     'image': 'durant.png',
#     'birthday': '1988-09-29',
#     'height': '208cm',
#     'weight': '108.9KG'
# }
#
# file = 'crypto.js'
# node = execjs.get()
# ctx = node.compile(open(file).read())
#
# js = f"getToken({json.dumps(item, ensure_ascii=False)})"
# print(js)
# result = ctx.eval(js)
# print(result)


'''使用requests调用nodeAPI'''
# import requests
# data = {
#     'name': '凯文-杜兰特',
#     'image': 'durant.png',
#     'birthday': '1988-09-29',
#     'height': '208cm',
#     'weight': '108.9KG'
# }
# url = 'http://localhost:3000'
# response = requests.post(url,json=data)
# print(response.text)

'''使用浏览器模拟JavaScript运行'''
from playwright.sync_api import sync_playwright
import requests

BASE_URL = 'https://spa2.scrape.center'
INDEX_URL = BASE_URL + '/api/movie?limit={limit}&offset={offset}&token={token}'
MAX_PAGE = 10
LIMIT = 10

context = sync_playwright().start()
browser = context.chromium.launch()
page = browser.new_page()
page.route(
    "/js/chunk-10192a00.243cb8b7.js",
    lambda route: route.fulfill(path="./chunk.js")
)

page.goto(BASE_URL)
page.wait_for_load_state('networkidle')
def get_token(offset):
    result = page.evaluate('''() => {
        return window.encrypt("%s", "%s")
    }''' % ('/api/movie', offset))
    return result

for i in range(MAX_PAGE):
    offset = i * LIMIT
    token = get_token(offset)
    index_url = INDEX_URL.format(limit=LIMIT, offset=offset, token=token)
    response = requests.get(index_url)
    print('response', response.json())




